import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/',
    name: 'layout',
    component: () =>
      import(/* webpackChunkName: "about" */ '../layout/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        // 导航元信息，可以在这个地方，添加一下需要的判断字段，或者标题等等
        meta: {
          auth: false,
          title: '首页',
        },
        component: () =>
          import(/* webpackChunkName: "about" */ '../views/Home.vue'),
      },
      {
        path: 'classify',
        name: 'classify',
        meta: {
          auth: false,
          title: '分类',
        },
        component: () => import('../views/Classify.vue'),
      },
      {
        path: 'cart',
        name: 'cart',
        meta: {
          auth: true,
          title: '购物车',
        },
        component: () => import('../views/Cart.vue'),
      },
      {
        path: 'mine',
        name: 'mine',
        meta: {
          auth: false,
          title: '我的',
        },
        component: () => import('../views/Mine.vue'),
      },
    ],
  },
  {
    path: '/vant-demo',
    name: 'vantDemo',
    meta: {
      auth: false,
      title: 'vant-demo',
    },
    component: () => import('../views/demo/vant/vant-demo.vue'),
  },
  {
    path: '/vmodel',
    name: 'vmodel',
    meta: {
      auth: false,
      title: 'v-model',
    },
    component: () => import('../views/demo/v-model/index.vue'),
  },

  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
      title: '登陆',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '*',
    component: () => import('../views/404.vue'),
  },
  {
    path: '/chat',
    name: 'chat',
    meta: {
      auth: false,
      title: '聊天界面',
    },
    component: () => import('../views/Chat.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 1. 路由拦截(你不管去哪个页面，都会先进入这个拦截函数)
// 导航守卫效果
// 如果有多个页面都想守卫，怎么解决？
router.beforeEach((to, from, next) => {
  // console.log(to.meta.auth, 'to')
  // if (to.name === 'cart') {
  // 一进入页面。就设置标题
  document.title = to.meta.title
  if (to.meta.auth) {
    // const token = localStorage.getItem('token')
    // 从vuex中获取到token,
    const token = store.state.login.token
    if (token) {
      next()
    } else {
      // 如果没有登陆，就跳登陆页面，并且带上这个页面的参数，以便一会儿跳转回来
      next({
        path: '/login',
        // query: { fullPath: to.fullPath },
      })
    }
  } else {
    next()
  }
  // next() // 往下走，继续访问的意思
})

export default router
